﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
using thousandclear.Data;
using thousandClear.Areas.Shop.Models;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Shop.Controllers
{
    public class ProductController : BaseController
    {
        // GET: Shop/Product
        public ActionResult Index(long? id, string openid)
        {
            AppSetting setting = new AppSetting();
            GoodViewModel list = new GoodViewModel();
            try
            {

                using (var db = new qianjingEntities())
                {
                    var goodddetail = db.D_ShopGood.FirstOrDefault(dsf => dsf.DSGID == id);
                    if (goodddetail != null)
                    {
                        list.DSGID = goodddetail.DSGID;
                        list.Name = goodddetail.Name;
                        list.Credit = goodddetail.Credit;
                        list.ImgDesc = goodddetail.ImgDesc.Replace("\n","<br/>");
                        list.ImgUrl = string.Format("{0}/{1}/{2}", setting.AppDomainName, "statics/upload/good/image", goodddetail.ImgUrl);
                    }

                    var Provinces = db.D_Angent.Where(a => a.RowStatus == 1 && a.datLevel == 1).ToList();
                    ViewBag.Provinces = JsonConvert.SerializeObject(Provinces);

                    //foreach (var item in records)
                    //{
                    //    list.Add(new ProjectModel
                    //    {
                    //        dimDesc = item.dimDesc,
                    //        dimName = item.dimName,
                    //        dimTotalRate = Convert.ToInt16(item.dimTotalRate),
                    //        DIMID = Convert.ToInt16(item.DIMID),
                    //    });
                    //}
                }
                ViewBag.OpenId = openid;

            }
            catch (Exception ex)
            {
                Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2fwww.qianjing-china.com%2fthousandclear%2fshop%Market&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
            }
            return View(list);

        }

        //HttpGet: Shop/Address
        [HttpGet]
        public string changeCustomerPlace(string id)
        {
            var query = "";
            using (var db = new qianjingEntities())
            {
                int idx = int.Parse(id);
                query = JsonConvert.SerializeObject(db.D_Angent.Where(a => a.datDATID == idx && a.RowStatus == 1).ToList());
            }
            return query;
        }

        #region---生成订单号----
        private string GenerateOrderSerialNo()
        {
            var ran = new Random();
            return string.Format("{0}{1}{2}", "YXG", DateTime.Now.ToString("yyMMddHHmmss"), GetRandStr(6).ToUpper());
        }
        private string GetRandStr(int count)
        {
            Random rnd = new Random();

            StringBuilder sb = new StringBuilder();

            string guid = Guid.NewGuid().ToString().Replace("-", "");

            for (int i = 0; i < count; i++)
            {
                var idx = rnd.Next(0, 32);
                sb.Append(guid.Substring(idx, 1));
            }

            return sb.ToString();
        }
        public string GenerateOrderRefundNo()
        {
            var ran = new Random();
            return string.Format("{0}{1}{2}", "YXGF", DateTime.Now.ToString("yyMMddHHmmss"), GetRandStr(6).ToUpper());
        }
        #endregion

        [HttpPost]
        public ActionResult Index(string data)
        {
            long orderId = 0;
            string openid = "";
            try
            {
                UtilNS.Util.WriteLog("已经进到订单");
                var post = JObject.Parse(data);
                //int way = post["way"].Value<int>();
                openid = post["openid"].Value<string>();

                var goodId = post["id"].Value<long>();

                var goodName = post["goodName"].Value<string>();
                var quantity = post["quantity"].Value<int>();


                //int regionId = post["regionId"].Value<int>();
                string receiveMan = post["receiveMan"].Value<string>();
                string receiveMobile = post["receiveMobile"].Value<string>();
                string receiveZipCode = post["receiveZipCode"].Value<string>();
                string receiveAddress = post["receiveAddress"].Value<string>();
                //string remark = post["remark"].Value<string>();
                // string size = post["size"].Value<string>();
                //string quality = post["quality"].Value<string>();

                int SelectProvince = post["SelectProvince"].Value<int>();
                int SelectCity = post["SelectCity"].Value<int>();
                int SelectBlock = post["SelectBlock"].Value<int>();


                //FeeApiController api = new FeeApiController();

                var newOrder = new O_Order_Info();
               
                UtilNS.Util.WriteLog("参数完全正常");
                using (var _db = new qianjingEntities())
                {
                    string custaddress = "";

                    var queryCountry = _db.D_Angent;
                    custaddress = queryCountry.FirstOrDefault(p => p.DATID == SelectProvince).datDesc.Trim()
                        + queryCountry.FirstOrDefault(c => c.DATID == SelectCity).datDesc.Trim()
                        + queryCountry.FirstOrDefault(b => b.DATID == SelectBlock).datDesc.Trim()
                        + receiveAddress;

                    UtilNS.Util.WriteLog("地址正常：" + custaddress);

                    var csm = _db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);

                    var good = _db.D_ShopGood.FirstOrDefault(a => a.DSGID == goodId);

                    if (good != null)
                    {
                        //锁定配额
                        //good.OnHold = good.OnHold + quantity;
                        UtilNS.Util.WriteLog("openid：" + openid);
                        newOrder = new O_Order_Info
                        {
                            Amount = good.Credit.Value * quantity,
                            PostFee = 0.00m,
                            SerialNo = GenerateOrderSerialNo(),
                            OrderTime = DateTime.Now,
                            Weight = "0",
                            Status = 0,
                            PayState = 0,
                            PayMode = 1,
                            CreatedTime = DateTime.Now,
                            UpdatedTime = DateTime.Now,

                            RefundNo = GenerateOrderRefundNo(),
                            RefundState = 0,
                            ReceiveAddress = custaddress,
                            ReceiveMan = receiveMan,
                            ReceiveMobile = receiveMobile,
                            //ReceiveRegion = regionId,
                            ReceiveZip = receiveZipCode,
                            OpenId = openid,
                            //Remark = remark,
                            ConsumerId = csm != null ? (int)csm.OCID : 2
                        };


                        _db.O_Order_Info.Add(newOrder);

                        _db.D_Order_list_info.Add(new D_Order_list_info
                        {
                            GoodId = (int)goodId,
                            GoodName = goodName,
                            OrderId = newOrder.Id,
                            Quantity = quantity,
                            Amount = good.Credit,
                            GoodImgUrl = good.ThumbUrl,
                            CreatedTime = DateTime.Now,
                            UpdatedTime = DateTime.Now
                        });


                        _db.SaveChanges();
                        UtilNS.Util.WriteLog("子订单添加成功：");

                        orderId = newOrder.Id;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            

            return RedirectToAction("Index", "MarketOrder", new { id = orderId, openid = openid });
        }
    }
}